global.APP = {};
global.startArgs = {};
APP.localProperty = {};


const express = require("express");
const fs = require("fs");

require("./core/tools"); //APP.tools

const minimist = require('minimist');
global.startArgs = minimist(process.argv.slice(2));

//配置文件初始化
const CONFIG_PATH = "property.js";
if (!fs.existsSync(CONFIG_PATH)) { //初始化
    APP.tools.mCopyFileSync(`./model/${CONFIG_PATH}`, `./${CONFIG_PATH}`);
}
//数据库初始化
const DATABASE_PATH = "data.db";
if (!fs.existsSync(DATABASE_PATH)) { //初始化
    APP.tools.mCopyFileSync(`./model/${DATABASE_PATH}`, `./${DATABASE_PATH}`);
}

require("./model/property");
require("./property");

require("./core/log");

APP.infoLog("INFO", "配置文件: property.js 文件");

//控制台颜色
const colors = require("colors");
colors.setTheme({
    silly: "rainbow",
    input: "grey",
    verbose: "cyan",
    prompt: "red",
    info: "green",
    data: "blue",
    help: "cyan",
    warn: "yellow",
    debug: "magenta",
    error: "red"
});
global.START_WAIT = (() => {
    const loading = new Set();
    let finishCb;
    let loadingAll, finishCount = 0;
    const wait = function(name) {
        APP.infoLog('初始化', `模块加载完毕: ${name}! ${`[${++finishCount}/${loadingAll}]`.brightYellow}`);
        loading.delete(name);
        if (loading.size) return;
        delete global.START_WAIT;
        finishCb();
    }
    wait.load = function(name, path) {
        if (name) {
            if (name.constructor.name === 'Array')
                for (let i in name) loading.add(name[i]);
            else loading.add(name);
        }
        setTimeout(() => require(path), 1);
    };
    wait.setCb = cb => {
        finishCb = cb;
        loadingAll = loading.size;
        if (!(loadingAll > 0)) {
            delete global.START_WAIT;
            finishCb();
        }
    };
    return wait;
})();

START_WAIT.load(['DB', 'DB_static'], './core/Data');


const app = express();
app.use(require('compression')()); //启用压缩传输


app.use((req, res, next) => {
    let realIp = APP.localProperty.useRealIpHeader && (req.headers['X-Real-IP'] || req.headers['x-forwarded-for']);
    if (realIp) realIp = realIp.split(",")[0];

    APP.infoLog('visit', `[${realIp||req.ip}]`.red + ` - ${req.url}`);
    next();
});

app.use('/-', require("./route/public"));
app.use('/--', require("./route/api"));
app.use('/', require("./route/main"));


var host = APP.localProperty.http_ip;
var port = APP.localProperty.http_port;
if (host == "::") host = "0.0.0.0";
START_WAIT.setCb(() => {
    if (startArgs.enPasswd) {
        let pwd = startArgs.enPasswd;
        console.log(`密码 "${`${pwd}`.yellow}" 的混淆存储值: `);
        console.log(require("./core/User").enPasswd(pwd).yellow);
        return;
    }

    app.listen(port, host, () => {
        APP.infoLog("HTTP", "HTTP 模块监听: [ http://" + ((host || "127.0.0.1").yellow) + ":" + port + " ]");
        APP.infoLog("INFO", "服务器已经启动");
    });
    require("./core/procexit");
});